package com.zx.onlineeducation.service.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zx.onlineeducation.common.servicebase.exception.OnlineEducationException;
import com.zx.onlineeducation.common.util.JwtUtils;
import com.zx.onlineeducation.common.util.MD5;
import com.zx.onlineeducation.common.util.ResultCodeEnum;
import com.zx.onlineeducation.service.ucenter.entity.MemberDO;
import com.zx.onlineeducation.service.ucenter.entity.vo.LoginVO;
import com.zx.onlineeducation.service.ucenter.entity.vo.RegisterVO;
import com.zx.onlineeducation.service.ucenter.mapper.MemberMapper;
import com.zx.onlineeducation.service.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 会员 服务实现类
 * </p>
 *
 * @author 郑雪
 * @since 2022-01-25
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberDO> implements MemberService {

    /**
     * Redis操作工具类（以字符串形式存入Redis缓存数据库）
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 会员登录
     *
     * @param loginVO 会员登录视图对象 {@link LoginVO}
     * @return token字符串
     * @author 郑雪
     * @since 2022-01-25
     */
    @Override
    public String login(LoginVO loginVO) {
        // 手机号
        String mobile = loginVO.getMobile();
        // 密码
        String password = loginVO.getPassword();
        if (StringUtils.isEmpty(mobile)) {
            throw new OnlineEducationException(ResultCodeEnum.MOBILE_NULL_ERROR);
        }
        if (StringUtils.isEmpty(password)) {
            throw new OnlineEducationException(ResultCodeEnum.PASSWORD_NULL_ERROR);
        }
        // 根据手机号查询会员
        MemberDO memberDO = this.getMemberByMobile(mobile);
        if (memberDO == null) {
            throw new OnlineEducationException(ResultCodeEnum.MOBILE_NOT_EXIST);
        }
        // 密码比对
        String memberDOPassword = memberDO.getPassword();
        String md5Password = MD5.encrypt(password);
        if (!Objects.equals(md5Password, memberDOPassword)) {
            throw new OnlineEducationException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 是否禁用
        Boolean disabled = memberDO.getDisabled();
        if (disabled) {
            throw new OnlineEducationException(ResultCodeEnum.ACCT_DISABLED);
        }

        // 返回token
        String id = memberDO.getId();
        String nickname = memberDO.getNickname();
        return JwtUtils.getJwtToken(id, nickname);
    }

    /**
     * 会员注册
     *
     * @param registerVO 会员注册视图对象 {@link RegisterVO}
     * @return 成功true，失败false
     * @author 郑雪
     * @since 2022-01-25
     */
    @Override
    public boolean register(RegisterVO registerVO) {
        // 手机号
        String mobile = registerVO.getMobile();
        // 密码
        String password = registerVO.getPassword();
        // 昵称
        String nickname = registerVO.getNickname();
        // 验证码
        String code = registerVO.getCode();
        if (StringUtils.isEmpty(mobile)) {
            throw new OnlineEducationException(ResultCodeEnum.MOBILE_NULL_ERROR);
        }
        if (StringUtils.isEmpty(password)) {
            throw new OnlineEducationException(ResultCodeEnum.PASSWORD_NULL_ERROR);
        }
        if (StringUtils.isEmpty(code)) {
            throw new OnlineEducationException(ResultCodeEnum.CODE_NULL_ERROR);
        }
        // 根据手机号查询会员是否已存在
        if (this.existMemberByMobile(mobile)) {
            throw new OnlineEducationException(ResultCodeEnum.MOBILE_ALREADY_EXIST);
        }
        // 验证码是否正确
        String codeRedis = stringRedisTemplate.opsForValue().get("code::" + mobile);
        if (!Objects.equals(code, codeRedis)) {
            throw new OnlineEducationException(ResultCodeEnum.CODE_ERROR);
        }
        // 如果昵称为空，生成昵称
        if (StringUtils.isEmpty(nickname)) {
            registerVO.setNickname("edu_"+ UUID.randomUUID().toString().replaceAll("-", "").substring(0,8));
        }
        // 密码加密
        registerVO.setPassword(MD5.encrypt(password));
        // 创建会员数据对象
        MemberDO memberDO = new MemberDO();
        BeanUtils.copyProperties(registerVO, memberDO);
        // 添加会员，返回结果
        return this.save(memberDO);
    }

    /**
     * 根据手机号查询会员
     *
     * @param mobile 手机号
     * @return 会员数据对象 {@link MemberDO}
     * @author 郑雪
     * @since 2022-01-25
     */
    @Override
    public MemberDO getMemberByMobile(String mobile) {
        QueryWrapper<MemberDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        return this.getOne(queryWrapper);
    }

    /**
     * 根据手机号查询会员是否存在
     *
     * @param mobile 手机号
     * @return 已存在true，不存在false
     * @author 郑雪
     * @since 2022-01-25
     */
    @Override
    public boolean existMemberByMobile(String mobile) {
        QueryWrapper<MemberDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 根据微信openid查询会员
     *
     * @param openid 微信openid（授权用户唯一标识）
     * @return 会员数据对象 {@link MemberDO}
     * @author 郑雪
     * @since 2022-01-28
     */
    @Override
    public MemberDO getMemberByOpenid(String openid) {
        QueryWrapper<MemberDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return this.getOne(queryWrapper);
    }
}
